/**
 * 数组转树
 * @param data			// []
 * @param id				// string|number
 * @param parentId	// string|number
 * **/
export function TreeDataTranslate(data: any, id: String = 'id', pid: String = 'pId') {
  let res = [];
  let temp = {};
  for (let i = 0; i < data.length; i++) {
    temp[data[i][id]] = data[i];
  }
  for (let k = 0; k < data.length; k++) {
    if (temp[data[k][pid]] && data[k][id] !== data[k][pid]) {
      if (!temp[data[k][pid]]['children']) {
        temp[data[k][pid]]['children'] = [];
      }
      temp[data[k][pid]]['children'].push(data[k]);
    } else {
      res.push(data[k]);
    }
  }
  return res;
}

/**
 * 时间戳转时间格式
 * **/
export function TimestampToDate(): String {
  let datetime = new Date();
  let year = datetime.getFullYear(); // 年
  let month = (datetime.getMonth() + 1 + '').padStart(2, '0'); // 月
  let day = (datetime.getDate() + '').padStart(2, '0'); // 日
  let hour = (datetime.getHours() + '').padStart(2, '0'); // 时
  let minute = (datetime.getMinutes() + '').padStart(2, '0'); // 分
  let second = (datetime.getSeconds() + '').padStart(2, '0'); // 秒

  return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
}

/**
 * 判断数据类型
 * @param data
 * @returns {String}
 * **/
export function TypeOf(data: any): String {
  const toString = Object.prototype.toString;
  const map = {
    '[object Boolean]': 'boolean',
    '[object Number]': 'number',
    '[object String]': 'string',
    '[object Function]': 'function',
    '[object Array]': 'array',
    '[object Date]': 'date',
    '[object RegExp]': 'regExp',
    '[object Undefined]': 'undefined',
    '[object Null]': 'null',
    '[object Object]': 'object',
    '[object FormData]': 'formData'
  };
  return map[toString.call(data)];
}

/**
 * copy
 * @param {string} value // copy的内容
 * @returns {Promise}
 * **/
export function Copy(value: string): Promise<void> {
  let input = document.createElement('input');
  input.style.display = 'none';
  input.value = value;
  input.select();
  const bool = document.execCommand('copy');
  if (bool) {
    return Promise.resolve();
  } else {
    return Promise.reject();
  }
}
